package com.liu.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 刘浩然
 * @Date: 2020/3/24 14:29
 */
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    //内存认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("root").password("123").roles("admin","dba")
            .and()
            .withUser("admin").password("123").roles("admin","user")
            .and()
            .withUser("sang").password("123").roles("user");

    }
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("admin")

                .antMatchers("/user/**")
                .access("hasAnyRole('admin','user')")

                .antMatchers("/db/**")
                .access("hasRole('admin')and hasRole('dba')")

                .anyRequest()
                .authenticated()
                .and()

                .formLogin()
                .loginProcessingUrl("/login")
//                .loginPage("/login_page")
                .usernameParameter("/name")
                .passwordParameter("/pwd")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        Object principal =auth.getPrincipal();//当前登录用户的信息，在登录成功后，可以获取当前登录用户的信息一起返回给客户端
                          resp.setContentType("application/json;character=utf-8");
                        PrintWriter out = resp.getWriter();
                        resp.setStatus(200);
                        Map<String,Object> map = new HashMap<>();
                        map.put("status",200);
                        map.put("msg",principal);
                        ObjectMapper om =new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();

                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;character=utf-8;charset=utf-8");
                        PrintWriter out =resp.getWriter();
                        resp.setStatus(401);
                        Map<String,Object> map =new HashMap<>();
                        map.put("status",401);
                        if( e instanceof LockedException){
                            map.put("msg","账号被锁定,登录失败！");
                        }else if(e instanceof BadCredentialsException){
                            map.put("msg","账号或密码输入错误,登录失败！");
                        }else if(e instanceof DisabledException){
                            map.put("msg","账户被禁用,登录失败！");
                        }else if( e instanceof AccountExpiredException){
                            map.put("msg","账户已过期,登录失败!");
                        }else  if( e instanceof CredentialsExpiredException){
                            map.put("msg","密码已过期,登录失败！");
                        }else {
                            map.put("msg","登录失败!");
                        }
                        ObjectMapper om =new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()

                .and()
                .logout()//注销
                .logoutUrl("/logout")
                .clearAuthentication(true)//移除认证信息
                .invalidateHttpSession(true)//使Session失效
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest req, HttpServletResponse resp, Authentication auth) {

                    }
                })
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        resp.sendRedirect("/login_page");
                    }

                })
                .and()
                .csrf()
                .disable();


    }

}
















